package sword;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * 剑指 Offer 06. 从尾到头打印链表
 *
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 *
 *
 *
 * 示例 1：
 *
 * 输入：head = [1,3,2]
 * 输出：[2,3,1]
 */
public class Sword0006 {

    public static void main(String[] args) {

    }

    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    static class Solution2 {
        public int[] reversePrint(ListNode head) {
            Stack<Integer> stack = new Stack<>();
            while (head !=null){
                stack.push(head.val);
                head = head.next;
            }

            int i=0;
            int[] arr = new int[stack.size()];
            while(!stack.isEmpty()){
                arr[i++] = stack.pop();
            }
            return arr;
        }
    }
    static class Solution1 {
        public int[] reversePrint(ListNode head) {
            if(head.next == null){
                return new int[]{head.val};
            }
            List<Integer> list = new ArrayList<>();
            list.addAll(Arrays.stream(reversePrint(head.next)).mapToObj(o->o).toList());
            int[] result = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                result[i] = list.get(i);
            }
            return result;
        }
    }
}
